package net.qqxh.resolve2text.impl;


import net.qqxh.resolve2text.File2TextResolve;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.stereotype.Component;


import java.io.*;

@Component
public class Xls2TextResolve implements File2TextResolve {
    private static String TYPE = "xls";

    @Override
    public String resolve(File file) throws IOException {

        InputStream is = null;
        HSSFWorkbook wb;
        ExcelExtractor extractor = null;
        String text = "";
        try {
            is = new FileInputStream(file);
            wb = new HSSFWorkbook(new POIFSFileSystem(is));
            extractor = new ExcelExtractor(wb);
            extractor.setFormulasNotResults(false);
            extractor.setIncludeSheetNames(false);
            text = extractor.getText();
            extractor.close();
        } catch (IOException e) {
            throw e;
        }finally {
            if(extractor!=null){
                try {
                    extractor.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return text;
    }

    @Override
    public String getType() {
        return TYPE;
    }
}
